const path = require('path')
const webpack = require('webpack')
const packageJson = require('./package.json')
const GitRevisionPlugin = require('git-revision-webpack-plugin')
const GitRevision = new GitRevisionPlugin()
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')
const TerserPlugin = require('terser-webpack-plugin')

function resolve(dir) {
  return path.join(__dirname, dir)
}

// check Git
function getGitHash() {
  try {
    return GitRevision.version()
  } catch (e) {}
  return 'unknown'
}
// eslint-disable-next-line no-unused-vars
const isProd = ['production'].includes(process.env.NODE_ENV)
// eslint-disable-next-line no-unused-vars
const assetsCDN = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios',
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    '//cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js',
    '//cdn.jsdelivr.net/npm/vue-router@3.5.1/dist/vue-router.min.js',
    '//cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
    '//cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js',
  ],
}

// qiankun子应用名称
const appName = process.env.VUE_APP_NAME

// vue.config.js
const vueConfig = {
  lintOnSave: false, // 禁用ESLint校验
  publicPath: process.env.VUE_APP_QIANKUN === 'true' ? `/${appName}/` : '/',
  outputDir: process.env.VUE_APP_QIANKUN === 'true' ? appName : 'dist', // 修改打包输出目录名称
  configureWebpack: {
    // qiankun子应用配置
    output: {
      // 把子应用打包成 umd 库格式
      library: `${appName}-[name]`,
      libraryTarget: 'umd',
      // webpack 5 需要把 jsonpFunction 替换成 chunkLoadingGlobal
      chunkLoadingGlobal: `webpackJsonp_${appName}`,
    },
    // 生产环境优化配置
    optimization: isProd ? {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            compress: {
              drop_console: true, // 删除console
              drop_debugger: true, // 删除debugger
              pure_funcs: ['console.log'] // 删除特定的console方法
            }
          }
        })
      ]
    } : {},
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin({
        contextRegExp: /^\.\/locale$/,
        resourceRegExp: /moment$/,
      }),
      new webpack.DefinePlugin({
        APP_VERSION: `"${packageJson.version}"`,
        GIT_HASH: JSON.stringify(getGitHash()),
        BUILD_DATE: buildDate,
      }),
    ],
    // en_US: `if prod, add externals`
    // zh_CN: `这里是用来控制编译忽略外部依赖的，与 config.plugin('html') 配合可以编译时引入外部CDN文件依赖`
    // externals: isProd ? assetsCDN.externals : {}
  },

  chainWebpack: (config) => {
    config.resolve.alias.set('@$', resolve('src'))

    // fixed svg-loader by https://github.com/damianstasik/vue-svg-loader/issues/185#issuecomment-1126721069
    const svgRule = config.module.rule('svg')
    // Remove regular svg config from root rules list
    config.module.rules.delete('svg')

    config.module
      .rule('svg')
      // Use svg component rule
      .oneOf('svg_as_component')
      .resourceQuery(/inline/)
      .test(/\.(svg)(\?.*)?$/)
      .use('babel-loader')
      .loader('babel-loader')
      .end()
      .use('vue-svg-loader')
      .loader('vue-svg-loader')
      .options({
        svgo: {
          plugins: [
            { prefixIds: true },
            { cleanupIDs: true },
            { convertShapeToPath: false },
            { convertStyleToAttrs: true },
          ],
        },
      })
      .end()
      .end()
      // Otherwise use original svg rule
      .oneOf('svg_as_regular')
      .merge(svgRule.toConfig())
      .end()

    // en_US: If prod is on assets require on cdn
    // zh_CN: 如果是 prod 模式，则引入 CDN 依赖文件，有需要减少包大小请自行解除依赖
    //
    // if (isProd) {
    //   config.plugin('html').tap(args => {
    //     args[0].cdn = assetsCDN
    //     return args
    //   })
    // }
  },

  css: {
    loaderOptions: {
      less: {
        modifyVars: {
          // Ant Design 4.x 主色系
          '@primary-color': '#2f54eb', // 经典蓝色
          '@link-color': '#2f54eb',
          '@success-color': '#52c41a',
          '@warning-color': '#faad14',
          '@error-color': '#f5222d',
          '@font-size-base': '14px',

          // Ant Design 4.x 文字色阶
          '@heading-color': 'rgba(0, 0, 0, 0.85)',
          '@text-color': 'rgba(0, 0, 0, 0.65)',
          '@text-color-secondary': 'rgba(0, 0, 0, 0.45)',
          '@disabled-color': 'rgba(0, 0, 0, 0.25)',

          // Ant Design 4.x 边框和分割线
          '@border-color-base': '#d9d9d9',
          '@border-color-split': '#f0f0f0',
          '@border-width-base': '1px', // 4.x 保留边框
          '@border-style-base': 'solid',

          // Ant Design 4.x 圆角系统 (更小的圆角)
          '@border-radius-base': '6px', // 4.x 默认圆角
          '@border-radius-sm': '2px',
          '@border-radius-lg': '4px',

          // Ant Design 4.x 阴影系统
          '@shadow-1-up': '0 -2px 8px rgba(0, 0, 0, 0.12)',
          '@shadow-1-down': '0 2px 8px rgba(0, 0, 0, 0.12)',
          '@shadow-1-left': '-2px 0 8px rgba(0, 0, 0, 0.12)',
          '@shadow-1-right': '2px 0 8px rgba(0, 0, 0, 0.12)',
          '@shadow-2': '0 4px 12px rgba(0, 0, 0, 0.15)',
          '@box-shadow-base':
            '0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08), 0 9px 28px 8px rgba(0, 0, 0, 0.05)',

          // Ant Design 4.x 间距系统
          '@padding-lg': '24px',
          '@padding-md': '16px',
          '@padding-sm': '12px',
          '@padding-xs': '8px',
          '@padding-xss': '4px',

          // Ant Design 4.x 组件特定样式
          '@btn-border-radius-base': '@border-radius-base',
          '@btn-border-width': '1px', // 4.x 按钮保留边框
          '@btn-shadow': '0 2px 0 rgba(0, 0, 0, 0.015)',
          '@btn-primary-shadow': '0 2px 0 rgba(0, 0, 0, 0.045)',

          // 输入框样式
          '@input-border-color': '@border-color-base',
          '@input-hover-border-color': '@primary-color',
          '@input-focus-border-color': '@primary-color',
          '@input-border-width': '1px',

          // 卡片样式
          '@card-radius': '@border-radius-base',
          '@card-shadow': '@box-shadow-base',
          '@card-border-color': '@border-color-split',

          // 表格样式
          '@table-border-radius-base': '@border-radius-base',
          '@table-border-color': '@border-color-split',
          '@table-header-bg': '#fafafa',

          // 菜单样式
          '@menu-border-color': '@border-color-split',
          '@menu-item-border': '1px solid transparent',

          // 布局样式
          '@layout-sider-background': '#001529',
          '@layout-body-background': '#f0f2f5',
          '@layout-header-background': '#001529',
          '@component-background': '#ffffff',

          // 分页器样式
          '@pagination-border-radius': '@border-radius-base',

          // 标签页样式
          '@tabs-border-color': '@border-color-split',
          '@tabs-hover-color': '@primary-color',

          // 模态框样式
          '@modal-border-radius': '@border-radius-base',
          '@modal-header-border-color-split': '@border-color-split',

          // 抽屉样式
          '@drawer-border-radius': '0',

          // 通知样式
          '@notification-border-radius': '@border-radius-base',
        },
        javascriptEnabled: true,
      },
    },
  },

  devServer: {
    // development server port 8000
    port: 8000,
    // qiankun子应用需要支持跨域
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    // If you want to turn on the proxy, please remove the mockjs /src/main.jsL11
    proxy: {
      '/bridgeApi': {
        target: 'http://47.100.43.220:8088',
        ws: false,
        changeOrigin: true,
      },
      '/modelApi': {
        target: 'http://47.100.43.220:8088',
        ws: false,
        changeOrigin: true,
      },
      '/heimdallrApi': {
        target: 'http://47.100.43.220:8088',
        ws: false,
        changeOrigin: true,
      },
    },
  },

  // disable source map in production
  productionSourceMap: false,
  // lintOnSave: undefined, // 已禁用ESLint校验
  // babel-loader no-ignore node_modules/*
  transpileDependencies: [],
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig
